package com.shaoyuwang;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 通过url方式,进行jdbc
 */
public class Demo2 {
    public static void main(String[] args) throws SQLException {

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setURL("jdbc:mysql://localhost:3306/lib_0403?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //连接
        Connection c = dataSource.getConnection();

        //sql语句
        String sql = "select * from books";

        //构建
        PreparedStatement statement = c.prepareStatement(sql);
        System.out.println(statement);

        //执行
        ResultSet rs= statement.executeQuery();
        while(rs.next()){//按表里面有的内容一列一列的输出 这里的while表示行数
            int bid = rs.getInt(1);
            String name = rs.getString("name");
            String count = rs.getString("count");
            String total = rs.getString("total");
            System.out.printf("%d  %s  %s  %s\n", bid, name, count, total);
        }

        //回收
        rs.close();
        statement.close();
        c.close();

    }
}
